/**
 * $Id: SubmitAndGetMTConnDeamon.java,v 1.7 2007/02/08 08:21:28 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.InitGatewayConfig;
import com.haoxi.gateway.common.Queue;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.connector.Connector;
import com.haoxi.gateway.messageconvertor.MessageConvertor;
import com.haoxi.gateway.runner.gzunicom.GZSubmit851MTThread;
import com.haoxi.gateway.runner.process.GetMTThread;

/**
 * 依据可下发MT的连接数下发
 * 
 * Revision History
 * 
 * 2006-6-12,star.Zhao,created it
 */
public class SubmitAndGetMTConnDeamon extends AbsConnectorDaemon {
    private static final Log log = LogFactory
            .getLog(SubmitAndGetMTConnDeamon.class);

    /**
     * 下发MT的队列
     */
    private Queue queue;
    private Queue reciveQueue;
    /**
     * 可下发MT的连接
     */
    private List connectors;

    /**
     * 下发MT的存储MapResp
     */
    private Map mapResp;

    /**
     * 消息转换器
     */
    private MessageConvertor convertor;

    /**
     * send synchronized object
     */
    private static Object SYN_SEND_MT_SPEED_OBJ = new Object();

    /**
     * 依据配置文件，获得下发速度： 单位（条/秒）
     */
    private static int submitSpeed = 0;
    private static long lastSendTime = 0;
    private static int countPerSencond = 0;

    /**
     * @param queue
     * @param connectors
     * @param mapResp
     */
    public SubmitAndGetMTConnDeamon(Queue queue, Queue reciveQueue,
            List connectors, Map mapResp, MessageConvertor convertor) {
        this.name = "SubmitMTConnDeamon";
        this.queue = queue;
        this.mapResp = mapResp;
        this.connectors = connectors;
        this.convertor = convertor;
        this.reciveQueue=reciveQueue;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.runner.AbsConnectorDaemon#getThreads()
     */
    public IRun[] getThreads() {
        IRun[] threads = null;
        int length = connectors.size();
        if (length > 0) {
            threads = new IRun[length + 1];
            setCurrentSubMTConnCount(length);
            String gatWaycode = InitGatewayConfig.getInstance()
                    .getGatewayInfo().getGatewayCode();
            // GatewayInfo gatewayInfo=GatewayInfo.
            // 如果有下发SubmitMT连接，启动GetMTThread，否则都不起动
            for (int i = 0; i < length; i++) {
                Connector connector = (Connector) connectors.get(i);
                // --------增加贵州联通的需求--------//
                if (gatWaycode.equals("100851")||gatWaycode.equals("10020")) {
                    threads[i] = new GZSubmit851MTThread(this.queue,this.reciveQueue, connector,
                            this.mapResp);
                } else {
                    threads[i] = new SubmitMTThread(this.queue, connector,
                            this.mapResp);
                }
            }
            threads[length] = new GetMTThread(this.queue, this.convertor);
        }

        return threads;
    }

    /**
     * 控制所有submitMTThread的下发速度
     */
    public static void controlSubmitMTSpeed() {
        Map sysCofn = RunnerMgr.getInstance().getSystemConf();
        submitSpeed = ((Integer) sysCofn.get(SYSConst.CONF_SUBMIT_SPEED))
                .intValue();
        synchronized (SYN_SEND_MT_SPEED_OBJ) {
            // 第一次下发,初始控制下发的参数
            long currentTime = System.currentTimeMillis();
            long numSecond = currentTime - lastSendTime;
            if (0 == lastSendTime || numSecond >= 1000) {
                lastSendTime = currentTime;
                countPerSencond = 1;
            } else {
                if (countPerSencond > submitSpeed) {
                    log.error("It is the limit speed of submitMt("
                            + submitSpeed + " per second) !!!");
                    try {
                        Thread.sleep(1000 - numSecond);
                    } catch (InterruptedException e) {
                        log
                                .error("----InterruptedException in SubmitAndGetMTConnDeamon.controlSubmitMTSpeed() ----"
                                        + e);
                    }
                    log.error("It is the limit speed of submitMt aweaken !!!");
                } else {
                    countPerSencond++;
                }

            }
        }
    }
}
